package com.example.notification;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RemoteViews;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.NotificationCompat;

import com.example.notification.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private static final int NOTIFICATION_ID = 100;

    public static final String ID_BASIC = "basic";
    public static final String ID_HIGH = "high";

    public static final String[] NOTIFICATION_STYLES = {
            "---请选择---", "基本样式", "悬浮样式", "自定义View",
            "长文本样式", "大图样式", "收件箱样式"};
    public static final String[] NOTIFICATION_STYLES_DESC = {
            "",
            "基本样式的通知",
            "高优先级的悬浮样式的通知",
            "自定义View的通知",
            "大文本样式的通知",
            "大图样式的通知",
            "收件箱样式的通知"
    };
    private ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        final ConstraintLayout root = binding.getRoot();
        setContentView(root);

        // 创建两个通知通道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel(ID_BASIC, "一般消息", NotificationManager.IMPORTANCE_DEFAULT);
            createNotificationChannel(ID_HIGH, "订阅消息", NotificationManager.IMPORTANCE_HIGH);
        }

        // 给Spinner控件设置数据适配器
        final ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, NOTIFICATION_STYLES);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        binding.spStyle.setAdapter(adapter);
        binding.spStyle.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        binding.tvDescription.setText(NOTIFICATION_STYLES_DESC[position]);
        if (position == 1) {
            showBasicNotification();
        } else if(position == 2) {
            showFullNotification();
        } else if(position == 3) {
            showCustomViewNotification();
        } else if(position == 4) {
            showBigTextNotification();
        } else if(position == 5) {
            showBigPictureNotification();
        } else if(position == 6) {
            showInboxNotification();
        }
    }

    // 发送一般消息
    private void showBasicNotification() {
        final Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        }
        // 创建通知
        final Notification notification = new NotificationCompat.Builder(this, ID_BASIC)
                .setSmallIcon(R.drawable.ic_message)
                .setContentTitle("会议时间")
                .setContentText("研讨会于今天下午1:30开始")
                .setContentIntent(pendingIntent)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.pic))
                .build();
        // 发送通知
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID, notification);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.cancel(NOTIFICATION_ID);
        manager.cancelAll();
    }

    /**
     * 创建通知通道
     *
     * @param channelId
     * @param channelName
     * @param importance
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel(String channelId, String channelName, int importance) {
        final NotificationChannel channel = new NotificationChannel(channelId, channelName, importance);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.createNotificationChannel(channel);
    }

    // 设置高重要性实现悬浮通知
    public void showFullNotification() {
        // 定义通知点击后跳转的Activity的Intent
        Intent intent = new Intent(this, SecondActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        }

        // 创建通知
        Notification notification = new NotificationCompat.Builder(this, ID_HIGH)
                .setSmallIcon(R.drawable.ic_importance)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.pic))
                .setAutoCancel(true)
                .setContentTitle("重要消息")
                .setContentText("紧急通知：计算机等级考试本周末开考！")
                .setFullScreenIntent(pendingIntent, true)
                .build();

        // 显示通知
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID + 1, notification);
    }

    // 自定义View的基本通知
    public void showCustomViewNotification() {
        // 通知的自定义布局
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_notification);
        // 通过控件id设置属性
        remoteViews.setImageViewResource(R.id.iv_pic, R.mipmap.ic_launcher_round);
        remoteViews.setTextViewText(R.id.tv_title, "热点新闻");
        remoteViews.setTextViewText(R.id.tv_content, "全国进入急冻模式，开始大幅度降温");

        // 定义启动Activity的Intent
        Intent intent = new Intent(this, SecondActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        }

        // 创建通知
        Notification notification = new NotificationCompat.Builder(this, ID_BASIC)
                .setSmallIcon(R.drawable.ic_message)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setCustomContentView(remoteViews)
                .build();

        // 显示通知
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.notify(NOTIFICATION_ID + 2, notification);
        }
    }

    // 长文本样式的通知
    private void showBigTextNotification() {
        // 定义启动Activity的Intent
        Intent intent = new Intent(this, SecondActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        }

        String msg = "Android的Notification有多种展示样式，可以应用NotificationCompat.BigTextStyle，" +
                "在通知的展开内容区域显示文本";

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pic);
        // 大文本
        Notification notification = new NotificationCompat.Builder(this, MainActivity.ID_BASIC)
                .setSmallIcon(R.drawable.ic_message)
                .setContentTitle("新邮件")
                .setContentText(msg)
                .setContentIntent(pendingIntent)
                .setLargeIcon(bitmap)
                .setAutoCancel(true)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .build();
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID + 3, notification);
    }

    // 大图样式的通知
    private void showBigPictureNotification() {
        // 定义启动Activity的Intent
        Intent intent = new Intent(this, SecondActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        }

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pic);
        // 大图片
        Notification notification = new NotificationCompat.Builder(this, MainActivity.ID_BASIC)
                .setSmallIcon(R.drawable.ic_message)
                .setContentIntent(pendingIntent)
                .setContentTitle("图片")
                .setContentText("查看你的屏幕截图")
                .setAutoCancel(true)
                .setLargeIcon(bitmap)
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .bigPicture(bitmap).bigLargeIcon(null))
                .build();
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID + 4, notification);
    }

    // 收件箱样式的通知
    private void showInboxNotification() {
        // 定义启动Activity的Intent
        Intent intent = new Intent(this, SecondActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
        } else {
            pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        }

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.pic);
        // 收件箱
        Notification notification = new NotificationCompat.Builder(this, MainActivity.ID_BASIC)
                .setSmallIcon(R.drawable.ic_email)
                .setContentIntent(pendingIntent)
                .setContentTitle("新邮件")
                .setContentText("5封新邮件")
                .setAutoCancel(true)
                .setLargeIcon(bitmap)
                .setStyle(new NotificationCompat.InboxStyle()
                        .addLine("如果想添加多个简短摘要行，可以应用NotificationCompat.InboxStyle。")
                        .addLine("可以添加多条内容文本，并且每条文本均截断为一行。")
                        .addLine("并不显示为 NotificationCompat.BigTextStyle 提供的连续文本行。")
                        .addLine("可以调用addLine()添加新行")
                        .addLine("可以通过使用HTML标记添加样式，比如加粗主题，以区分消息主题和内容"))
                .build();
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        manager.notify(NOTIFICATION_ID + 5, notification);
    }
}